package com.hs.srm.api.modules.pricemanagement.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hs.srm.admin.modules.pricemanagement.entity.HistoricalPriceEntity;
import com.hs.srm.admin.modules.pricemanagement.entity.InquiryQuotationEntity;
import com.hs.srm.admin.modules.pricemanagement.service.HistoricalPriceService;
import com.hs.srm.admin.modules.pricemanagement.service.InquiryQuotationService;
import com.hs.srm.admin.modules.requisition.entity.NproPurchRequestItemEntity;
import com.hs.srm.admin.modules.requisition.entity.ProPurchRequestItemEntity;
import com.hs.srm.admin.modules.requisition.entity.SamplePurchRequestItemEntity;
import com.hs.srm.admin.modules.requisition.service.NproPurchRequestItemService;
import com.hs.srm.admin.modules.requisition.service.ProPurchRequestItemService;
import com.hs.srm.admin.modules.requisition.service.SamplePurchRequestItemService;
import com.hs.srm.common.utils.DateUtils;
import com.hs.srm.common.utils.R;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import sunnykid.text.SunnykidText;

import java.math.BigDecimal;
import java.util.*;

/**
 * @author yanfei
 * @date 2019年6月20日
 */
@Controller
@RequestMapping("/api/parity")
@EnableAutoConfiguration

public class ParityApi {

    @Autowired
    private InquiryQuotationService inquiryQuotationService;

    @Autowired
    private NproPurchRequestItemService nproPurchRequestItemService;

    @Autowired
    private SamplePurchRequestItemService samplePurchRequestItemService;

    @Autowired
    private ProPurchRequestItemService proPurchRequestItemService;
    @Autowired
    private HistoricalPriceService historicalPriceService;

    /**
     * OA价格审批审核结果
     * <p>
     * 传递参数：
     * quotationId : 报价单id（必选参数）
     * result : 审核结果，true未通过，false为未通过（可选参数）
     * msg : 审核意见（可选参数）
     * 参数示例
     * 审核通过：{"quotationId":"123456","result":true, "msg":"同意"}
     * 审核不通过：{"quotationId":"123456","result":false, "msg":"价格太高，不同意"}
     * 客户端调用示例：
     * String JSONString = "{\"quotationId\":\"123456\",\"result\":true, \"msg\":\"同意\"}";
     * HttpClient client = new HttpClient("http://127.0.0.1:8085/hssrm/api/parity/shenheResult");
     * Response response = client.post(new Parameter("jsonData", JSONString));
     * <p>
     * {"result":true,"msg":"通过","inquiryId":"b77f38ef60854a89a5458bde13bc1a27",
     * "quotationId":"38ddde5a196a40ed88385676ddf80147","processId":"16c0958dd0e6157452158df4b89a2cf6"}
     */
    @RequestMapping(value = "/shenheResult", method = RequestMethod.POST)
    @ResponseBody
    public R shenheResult(String jsonData) {
        //{"result":true,"msg":"通过测试通过","quotationId":"372da90b4e0d473c9bbfbf1d0f914c77"}
        JSONObject jsonObject = JSON.parseObject(jsonData);
        //057612a0da394e36a82ce4346daba878 返回来询价id
        if (jsonObject != null) {
            Map<String, String> quotationId = (Map<String, String>) JSON.parse(jsonObject.getString("quotationId"));

            String oaDocId = jsonObject.getString("processId");
            List<InquiryQuotationEntity> inquiryQuolist = inquiryQuotationService.findByOaDocId(oaDocId);
            //非生产性
            List<String> ids = new ArrayList<>();
            //生产性
            List<String> idss = new ArrayList<>();
            //样品 审批不通过id
            List<String> sampleDenied = new ArrayList<>();
            Set<String> strsetquotationId = new TreeSet<String>();
            Set<String> strset = new TreeSet<String>();
            Set<String> set = new TreeSet<String>();
            //非生产性
            Set<String> setnpitemid = new TreeSet<>();
            //生产性
            Set<String> setpitemid = new TreeSet<>();
            //样品
            Set<String> sampleItemid = new TreeSet<>();

            HistoricalPriceEntity historicalPriceEntity = new HistoricalPriceEntity();

            for (InquiryQuotationEntity inquiryQuotation : inquiryQuolist) {
                strset.add(inquiryQuotation.getQuotationId());
            }
            CollectionUtils.addAll(strsetquotationId, quotationId.keySet());
            set.addAll(strset);//所有的报价单id
            //strsetquotationId 审核通过的报价单id
            set.removeAll(strsetquotationId);//驳回的报价单id
            //审批通过
            Object[] quotationStr = quotationId.keySet().toArray();
            for (Object st : quotationStr) {
                for (InquiryQuotationEntity inquiryQuotation : inquiryQuolist) {
                    if (inquiryQuotation.getQuotationId().equals(st)) {
                        String str = jsonObject.getString("result");
                        if ("true".equals(str)) {
                            inquiryQuotation.setState(InquiryQuotationEntity.STATE_SHENHETONGGUO);
                            inquiryQuotation.setCreatedDate(DateUtils.currentDateTime());
                            //设置最终价格、总价和单价
                            String lastPrice = quotationId.get(st);
                            //购买数量
                            String purchaseCnt = inquiryQuotation.getPurchaseCnt();
                            //最终价格作为含税价，乘数量计算总价,乘1000是防止价格小数位直接乘 出现精度问题
                            double totlePrice = Double.parseDouble(lastPrice) * 1000 * Double.parseDouble(purchaseCnt) / 1000;
                            inquiryQuotation.setLastEnquiryPrice(lastPrice);
                            //修改含税价为最终价格
                            inquiryQuotation.setPrice(new BigDecimal(lastPrice));
                            inquiryQuotation.setTotalPrice(new BigDecimal(totlePrice));
                            inquiryQuotationService.updateById(inquiryQuotation);
                        }
                    }
                }
            }
            //审批不通过
			/*for (String str : set) {
				InquiryQuotationEntity inquiryQuotationEntity =inquiryQuotationService.selectById(str);
				inquiryQuotationEntity.setState(InquiryQuotationEntity.STATE_SHENHEBOHUI);
				inquiryQuotationEntity.setCreatedDate(DateUtils.currentDateTime());
				inquiryQuotationService.updateById(inquiryQuotationEntity);
				if("PR".equals(inquiryQuotationEntity.getRequestCode().substring(0, 2))){
					setnpitemid.add(inquiryQuotationEntity.getNpkId());
				}else{
					setpitemid.add(inquiryQuotationEntity.getNpkId());
				}
			}  */

            if (strsetquotationId != null && strsetquotationId.size() > 0) {
                //审批通过
                for (String str : strsetquotationId) {
                    InquiryQuotationEntity inquiryQuotationEntity = inquiryQuotationService.selectById(str);
                    inquiryQuotationEntity.setState(InquiryQuotationEntity.STATE_SHENHETONGGUO);
                    inquiryQuotationEntity.setCreatedDate(DateUtils.currentDateTime());
                    inquiryQuotationService.updateById(inquiryQuotationEntity);
                    if ("PR".equals(inquiryQuotationEntity.getRequestCode().substring(0, 2))) {
                        setnpitemid.add(inquiryQuotationEntity.getNpkId());
                    } else if (inquiryQuotationEntity.getRequestCode().indexOf("S") >= 0) {
                        sampleItemid.add(inquiryQuotationEntity.getNpkId());
                    } else {
                        setpitemid.add(inquiryQuotationEntity.getNpkId());
                    }
                }
            }
            if (!set.isEmpty()) {
                //审批不通过
                for (String str : set) {
                    InquiryQuotationEntity inquiryQuotationEntity = inquiryQuotationService.selectById(str);
                    inquiryQuotationEntity.setState(InquiryQuotationEntity.STATE_SHENHEBOHUI);
                    inquiryQuotationEntity.setCreatedDate(DateUtils.currentDateTime());
                    inquiryQuotationService.updateById(inquiryQuotationEntity);
                    if ("PR".equals(inquiryQuotationEntity.getRequestCode().substring(0, 2))) {
                        ids.add(inquiryQuotationEntity.getNpkId());
                    } else if (inquiryQuotationEntity.getRequestCode().indexOf("S") >= 0) {
                        sampleDenied.add(inquiryQuotationEntity.getNpkId());
                    } else {
                        idss.add(inquiryQuotationEntity.getNpkId());
                    }
                }
            }

            // 非生产的不通过
            if (ids != null && ids.size() > 0) {
                List<NproPurchRequestItemEntity> list = this.nproPurchRequestItemService.selectBatchIds(ids);
                for (NproPurchRequestItemEntity nproPurchRequestItemEntity : list) {
                    nproPurchRequestItemEntity.setGoodsStatus(NproPurchRequestItemEntity.STATE_SHENHEBOHUI);
                    this.nproPurchRequestItemService.insertOrUpdate(nproPurchRequestItemEntity);
                }
            }
            // 生产性不通过
            if (idss != null && idss.size() > 0) {
                List<ProPurchRequestItemEntity> list = this.proPurchRequestItemService.selectBatchIds(idss);
                for (ProPurchRequestItemEntity proPurchRequestItemEntity : list) {
                    proPurchRequestItemEntity.setGoodsStatus(ProPurchRequestItemEntity.STATE_SHENHEBOHUI);
                    this.proPurchRequestItemService.insertOrUpdate(proPurchRequestItemEntity);
                }
            }
            // 样品不通过
            if (sampleDenied != null && sampleDenied.size() > 0) {
                List<SamplePurchRequestItemEntity> list = samplePurchRequestItemService.selectBatchIds(sampleDenied);
                for (SamplePurchRequestItemEntity sampleRequestItemEntity : list) {
                    sampleRequestItemEntity.setGoodsStatus(SamplePurchRequestItemEntity.STATE_SHENHEBOHUI);
                    samplePurchRequestItemService.insertOrUpdate(sampleRequestItemEntity);
                }
            }
            //非生产的通过
            if (setnpitemid != null && setnpitemid.size() > 0) {
                for (String st : setnpitemid) {
                    NproPurchRequestItemEntity nproPurchRequestItemEntity = this.nproPurchRequestItemService.selectById(st);
                    nproPurchRequestItemEntity.setGoodsStatus(NproPurchRequestItemEntity.STATE_SHENHETONGGUO);
                    this.nproPurchRequestItemService.insertOrUpdate(nproPurchRequestItemEntity);
                }
            }
            // 生产性通过
            if (setpitemid != null && setpitemid.size() > 0) {
                for (String st : setpitemid) {
                    ProPurchRequestItemEntity proPurchRequestItemEntity = this.proPurchRequestItemService.selectById(st);
                    proPurchRequestItemEntity.setGoodsStatus(ProPurchRequestItemEntity.STATE_SHENHETONGGUO);
                    this.proPurchRequestItemService.insertOrUpdate(proPurchRequestItemEntity);
                }
            }
            // 样品通过
            if (sampleItemid != null && sampleItemid.size() > 0) {
                for (String st : sampleItemid) {
                    SamplePurchRequestItemEntity samplePurchRequestItemEntity = samplePurchRequestItemService.selectById(st);
                    samplePurchRequestItemEntity.setGoodsStatus(SamplePurchRequestItemEntity.STATE_SHENHETONGGUO);
                    samplePurchRequestItemService.insertOrUpdate(samplePurchRequestItemEntity);
                }
            }
            /***************2019-07-24************************/
            for (String str : strsetquotationId) {
                InquiryQuotationEntity inquiryQuotation = inquiryQuotationService.selectById(str);
                if ("PR".equals(inquiryQuotation.getRequestCode().substring(0, 2)) || "S".equals(inquiryQuotation.getRequestCode().substring(0, 1)) && inquiryQuotation.getState() == 3) {
                    historicalPriceEntity.setHistoricalPriceId(SunnykidText.getUUID());
                    historicalPriceEntity.setVendorCode(inquiryQuotation.getVendorCode());
                    historicalPriceEntity.setVendorName(inquiryQuotation.getVendorName());
                    historicalPriceEntity.setPrice(inquiryQuotation.getPrice());
                    historicalPriceEntity.setPriceUnit(inquiryQuotation.getPoPriceUnit());
                    historicalPriceEntity.setTaxCode(inquiryQuotation.getTaxCode());
                    historicalPriceEntity.setCreatedBy(inquiryQuotation.getCreatedBy());
                    historicalPriceEntity.setRequestCode(inquiryQuotation.getRequestCode());
                    historicalPriceEntity.setNpkId(inquiryQuotation.getNpkId());
                    historicalPriceEntity.setCurrency(inquiryQuotation.getCurrency());
                    historicalPriceEntity.setWerks(inquiryQuotation.getWerks());
                    historicalPriceEntity.setMaterialCode(inquiryQuotation.getMaterialCode());
                    historicalPriceEntity.setMaterialDesc(inquiryQuotation.getMaterialDesc());
                    historicalPriceEntity.setPurchaseGrp(inquiryQuotation.getPurchaseGrp());
                    historicalPriceEntity.setPurchaseOrg(inquiryQuotation.getPurchaseOrg());
                    historicalPriceEntity.setRemark(inquiryQuotation.getRemark());
                    historicalPriceEntity.setCreatedDate(inquiryQuotation.getCreatedDate());
                    //historicalPriceEntity.setItemNo(inquiryQuotation.geti);   后续用的话在修改(目前不用)
                }
            }
            /***************2019-07-24************************/

        } else {
            return R.error();
        }
        return R.ok();
    }

}
